﻿@using KPIS.GERP;
@using KPIS.GERP.Models;
@using KPIS.GERP.Models.SYS;
@using KPIS.GERP.Models.Class;

@{
    Layout = null;
    string strType = ConvertUtility.MakeObjectToStringDefaultEmpty(HttpContext.Current.Request["strParcelType"]);
    int intResItemId = ConvertUtility.ConvertOrDefaultObjectInt(HttpContext.Current.Request["intResItemId"]);
    int? intProjId = ConvertUtility.ConvertOrDefaultObjectInt(HttpContext.Current.Request["intProjectId"]);
    int intWhId = ConvertUtility.ConvertOrDefaultObjectInt(HttpContext.Current.Request["intWhId"]);
    intProjId = intProjId == 0 ? null : intProjId;
}

@if (string.IsNullOrEmpty(strType) || intResItemId == 0 || !intProjId.HasValue || intWhId == 0)
{
    @:ข้อมูลระบุไม่ครบ
}
else
{
    // int[] intProjExpIds;
    decimal quantityAvailable = 0;
    decimal quantityRequest = 0;
    decimal quantityDispense = 0;
    var statusNames = new Dictionary<string, string>();
    Dictionary<string, string> cssClasses = new Dictionary<string, string>();
    var result = new Dictionary<DateTime, object>();
    var context = new GERPContext(false);

    var service = new KPIS.GERP.WEB.GIMS.RequestParcelService.RequestParcelServiceClient();

    foreach (var statusCode in new[] {"U", "W", "D", "A", "P", "R", "J"})
    {
        statusNames[statusCode] = service.GetStatusName(statusCode);
    }

    cssClasses["U"] = "text-info";
    cssClasses["A"] = "text-success";
    cssClasses["W"] = "text-warning";
    cssClasses["P"] = "muted";
    cssClasses["J"] = "red";
    cssClasses["D"] = "red";
    cssClasses["R"] = "muted";

    //intProjExpIds = (from f in context.ProjectExpenses
    //    join g in context.Projects on f.ProjId equals g.ProjId
    //    where g.ProjId == intProjId
    //    select f.ProjExpId).ToArray();

    var wh = context.Warehouses.Find(intWhId);

    if (strType == "OS") // วัสดุ
    {

        var ListQuantity = (from a in context.OfficeSuppliesLots.Include(o => o.ReceiveDtl.Received.DeliveryNote)
            .Include(o => o.OfficeSupplyLotStatus).Include(o => o.ReceiveDtl).Include(o => o.MasUnit)
            where a.ResItemId == intResItemId && a.WhId == intWhId &&
                  a.RecordStatus != KPIS.GERP.Models.SYS.RecordStatus.DeletedStatus /* &&
                  21/5/2558 ไม่ต้องคำนึงโครงการ ก็สามารถเบิกได้
                   (intProjExpIds.Contains(a.ProjExpId??0) || a.ProjExpId == null)*/
            select a).OrderByDescending(o => o.CreatedWhen);


        var ListQuantityDispense = (from a in context.RequestParcelDtls
            .Include(o => o.RequestParcel.WarehousePermit.Warehouse)
            .Include(o => o.MasResourceItem.MasUnit)
            where
                a.RequestParcel.RecordStatus != KPIS.GERP.Models.SYS.RecordStatus.DeletedStatus
                && a.RecordStatus != KPIS.GERP.Models.SYS.RecordStatus.DeletedStatus
                && a.ResItemId == intResItemId
                && a.RequestParcel.WarehousePermit.WhId == intWhId
            select a).OrderByDescending(o => o.RequestParcel.WantedDate);

        foreach (var l in ListQuantity)
        {
            result.Add(l.CreatedWhen.Value, l);
        }

        foreach (var l in ListQuantityDispense)
        {
            result.Add(l.CreatedWhen.Value, l);
        }
    }
    else // ครุภัณฑ์ สิ่งก่อสร้าง
    { 
        var list = (from a in context.Assets where a.ResItemId == intResItemId && a.WhId == intWhId && a.JobSiteId == null select a)
            // 21/5/2558 ไม่ต้องคำนึงโครงการ ก็สามารถเบิกได้ .Where(x => intProjExpIds.Contains(x.ProjExpId??0) || x.ProjExpId == null)
            .OrderByDescending(o => o.CreatedWhen).ToList();

        foreach (var l in list.GroupBy(o => new {o.AssetDate, o.RecordStatus, o.ResItemId}))
        {
            result.Add(l.Key.AssetDate, l.ToList());
        }

        var assetIds = list.Select(o => o.AssetId).ToArray();

        var listMm = context.MovementHistorys.Include("Asset").Where(a=>assetIds.Contains(a.AssetId) && a.RecordStatus != "D")
            .OrderByDescending(o => o.CreatedWhen);

        foreach (var l in listMm)
        {
            result.Add(l.CreatedWhen.Value, l);
        }
        
    }
    var result2 = result.OrderByDescending(o => o.Key);
    <ul>
        @foreach (var obj in result2)
        {
            if (obj.Value.GetType() == typeof (OfficeSuppliesLot))
            {
                var supplyLot = (OfficeSuppliesLot) obj.Value;
                var unitName = supplyLot.MasUnit != null ? supplyLot.MasUnit.Name : "";
                quantityAvailable += supplyLot.ReceiveDtl.Quantity;
                var dn = supplyLot.ReceiveDtl.Received.DeliveryNote;

                string projName = (from pex in context.ProjectExpenses
                    join p in context.Projects on pex.ProjId equals p.ProjId
                        where pex.ProjExpId == supplyLot.ProjExpId
                            select p.Name).FirstOrDefault();
                         
                
                <li>
                    @obj.Key.ToShortDateString() - 
                    <span title="@(projName)">[รับ] ล็อต @supplyLot.LotNo</span> |                               
                    <a href="@Url.Action("Details", "ReceiveParcel", new { id = supplyLot.ReceiveDtl.ReceiveId})" target="_blank"
                       title="@supplyLot.ReceiveDtl.Received.ReceiveCode - @supplyLot.ReceiveDtl.Received.ReceiveName">
                        @supplyLot.ReceiveDtl.Received.ReceiveCode <i class="icon-external-link"></i>
                    </a> |  
                    @if (dn != null)
                    {
                        <a href="@Url.Action("Details", "DeliveryNote", new {id = supplyLot.ReceiveDtl.Received.DnId})" target="_blank"
                           title="@dn.Code - @dn.Name">@dn.Code <i class="icon-external-link"></i></a>
                    }
                                                                                                                               ,
                    รับจำนวน @supplyLot.ReceiveDtl.Quantity.ToString("##,##0.##")@unitName,
                    ใช้ไปแล้ว @((supplyLot.ReceiveDtl.Quantity - supplyLot.Quantity).ToString("##,##0.##"))@unitName, 
                    คงเหลือ @supplyLot.Quantity.ToString("##,##0.##")@unitName 
                    (สถานะ @supplyLot.OfficeSupplyLotStatus)
                </li>
            }

            if (obj.Value.GetType() == typeof (RequestParcelDtl))
            {
                var reqParcelDtl = (RequestParcelDtl) obj.Value;
                var unitName = reqParcelDtl.MasResourceItem.MasUnit != null ? reqParcelDtl.MasResourceItem.MasUnit.Name : "";
                var recordFix = reqParcelDtl.RequestParcel.RecordStatus == "U" ? "W" : reqParcelDtl.RequestParcel.RecordStatus;
                if (reqParcelDtl.DispenseStatus == "true")
                {
                    quantityDispense += reqParcelDtl.Quantity ?? 0;
                }
                quantityRequest += reqParcelDtl.Quantity ?? 0;


                <li>
                    @obj.Key.ToShortDateString() - 
                    [เบิก]
                    <a href='@Url.Content("~/RequestParcel/Details/" + reqParcelDtl.RequestParcel.ReqParcelId)' target='_blank' 
                       title='@reqParcelDtl.RequestParcel.RequestName'>
                        @reqParcelDtl.RequestParcel.IcmReqCode 
                        <span class="@cssClasses[recordFix]">@statusNames[recordFix]</span>
                    </a>, เบิกจำนวน @((reqParcelDtl.Quantity ?? 0).ToString("##,##0.##")) @unitName (@(reqParcelDtl.DispenseStatus == "true" ? "จ่ายแล้ว" : "ยังไม่จ่าย"))
                </li>

            }

            if (obj.Value.GetType() == typeof (List<Asset>))
            {
                var assets = (List<Asset>) obj.Value;
                var asset = assets[0];
                var unitName = asset.MasUnit != null ? asset.MasUnit.Name : "";

                quantityAvailable += assets.Count;
                quantityRequest += 0;
                quantityDispense += 0;


                <li>                @obj.Key.ToShortDateString() - 
                    [@(asset.RecordStatus == "D" ? "จ่าย" : "รับ")]
                    จำนวน @assets.Count().ToString("##,##0.##")
                    @unitName
                    (Serial: @(string.Join(",", assets.Select(o => o.SerialNumber))))
                </li>
            }
            
            
            if (obj.Value.GetType() == typeof (MovementHistory))
            {
                var assetmm = (MovementHistory)obj.Value;
                var unitName = assetmm.Asset.MasUnit != null ? assetmm.Asset.MasUnit.Name : "";
                  
                quantityDispense += 1;
                 
                <li>
                                    @obj.Key.ToShortDateString() - 
                    [จ่าย]
                    จำนวน 1 @unitName
                    (Serial: @assetmm.Asset.AssetName)
                </li>
            }
        }
     
    </ul>

    <strong>
        @(wh != null ? wh.Name : "(ไม่เลือกคลังในใบเบิก?)")
        จำนวนที่รับเข้า @quantityAvailable.ToString("##,##0.##"),
        เบิก @quantityRequest.ToString("##,##0.##"),
        จ่ายแล้ว @quantityDispense.ToString("##,##0.##"),
        เหลือจริง @((quantityAvailable - quantityDispense).ToString("##,##0.##")),
        สามารถเบิกได้ @((quantityAvailable - quantityRequest).ToString("##,##0.##"))
        @(quantityAvailable - quantityRequest > 0 ? "" : "(เบิกไม่ได้)")
    </strong>
}